package com.ktjiaoyu.controller;
import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.StorageRecord;
import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.StorageService;
import com.ktjiaoyu.service.SupplierService;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @return 13141
 * 2025/7/8
 * 19:06
 */
@Controller
@RequestMapping("/main/storageRecord")
public class StorageController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(StorageController.class);
    @Resource
    private StorageService storageService;
    @Resource
    private SupplierService supplierService;
    // 分页查询入库记录列表
    @RequestMapping("/page")
    public String page(Model model, StorageRecord condition,
                       @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Page<StorageRecord> page = null;
        try {
//            查询用户的分页信息
            page = storageService.findPage(condition, pageNo, pageSize);
//            查询所有的角色信息
            List<Supplier> supplierList = supplierService.getSupplierList();
//            将分页数据、角色列表和查询条件设置到模型数据中
            model.addAttribute("pageInfo", page);
            model.addAttribute("supplierList", supplierList);
            model.addAttribute("condition", condition);
        } catch (Exception e) {
            LOGGER.error("StorageController 中的 page 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "storageRecord/page";
    }
    //    跳转到 save.jsp 页面的接口
    @GetMapping("/save")
    public String toSave(Model model) {
        List<Supplier> supplierList = null;
        try {
            supplierList = supplierService.getSupplierList();
//            有角色下拉框需要数据
            model.addAttribute("supplierList", supplierList);
//            回显数据时需要 storageRecord, 这里给个空对象避免出错
            model.addAttribute("storageRecord", new StorageRecord());
        } catch (Exception e) {
            LOGGER.error("StorageController 中的 toSave()方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "storageRecord/save";
    }
    //    保存或修改数据接口
    @PostMapping("/save")
    public String doSave(StorageRecord storageRecord) {
        try {
//           通过父类的 session 方法获取登录用户，由于泛型自动转换无需强转
            SysUser loginUser = session(Constants.SESSION_USER);
            if (storageRecord.getId() == null) {
//                如果是添加用户，关联创建用户为当前登录用户
                storageRecord.setCreatedUserId(loginUser.getId());
                storageRecord.setCreatedTime(new Date());
            } else {
//                如果是修改用户，关联修改用户为当前登录用户
                storageRecord.setUpdatedUserId(loginUser.getId());
                storageRecord.setUpdatedTime(new Date());
            }
//            新增和修改公用同一个业务方法
            boolean ok = storageService.saveOrUpdate(storageRecord);
            if (ok) {
//                保存成功，跳回列表界面
                return redirect("/main/storageRecord/page");
            }
        } catch (Exception e) {
            LOGGER.error("StorageController 中的 doSave 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "storageRecord/save";
    }
    //    查询入库记录信息并跳转修改页（共用 save.jsp）
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model) {
        StorageRecord storageRecord = null;
        List<Supplier> supplierList = null;
        try {
            storageRecord = storageService.findById(id);
            supplierList = supplierService.getSupplierList();
//            有角色下拉框需要数据
            model.addAttribute("supplierList", supplierList);
//            回显数据时需要 storageRecord,这里给个空对象避免出错
            model.addAttribute("storageRecord", storageRecord);
        } catch (Exception e) {
            LOGGER.error("StorageController 中的 toEdit方法执行出现错误。", e);
            throw new RuntimeException(e);
        }
        return "storageRecord/save";
    }
    //    根据 srCode 查找入库记录
    @ResponseBody
    @GetMapping("/srCodeExist")
    public String accountExist(@RequestParam("srCode") String srCode) {
        LOGGER.debug("检查入库编码 srCode={}的入库记录是否存在", srCode);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(srCode)) {
            resultMap.put("exist", 0);
        } else {
            try {
                StorageRecord storageRecord = storageService.findBySrCode(srCode);
                if (null != storageRecord) {
//                    已经存在，设置为1
                    resultMap.put("exist", 1);
                } else {
                    resultMap.put("exist", 0);
                }
            } catch (Exception e) {
                LOGGER.error("StorageController 中的" + "srCodeExist方法执行出现错误。", e);
                resultMap.put("error", "出现异常，请联系管理员处理！");
            }
        }
        return JSON.toJSONString(resultMap);
    }
    // 查看入库记录详情
    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, Model model) {
        StorageRecord storageRecord = null;
        try {
            storageRecord = storageService.findById(id);
            model.addAttribute("storageRecord", storageRecord);
        } catch (Exception e) {
            LOGGER.error("StorageController 中的 view 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "storageRecord/view";
    }
    // 根据 id 删除入库记录
    @ResponseBody
    @DeleteMapping("/del/{id}")
    public Map ajaxDel(@PathVariable("id") Long id,
                       Model model) {
        HashMap<String, Integer> resultMap = new HashMap<String, Integer>();
        Integer info = 0;
        try {
            info = storageService.deleteStorage(id);
            if (info != 0) {
                resultMap.put("code", 200);
                resultMap.put("data", info);
            } else {
                resultMap.put("code", 500);
            }
        } catch (Exception e) {
            LOGGER.error("StorageController 中的 ajaxDel 方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        // return JSON.toJSONString(resultMap);
        return resultMap;
    }
}
